package com.ternnetwork.clustersyn.boot;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.ternnetwork.clustersyn.model.AppInstance;
import com.ternnetwork.clustersyn.model.Cluster;
import com.ternnetwork.clustersyn.model.ServerNode;
import com.ternnetwork.clustersyn.util.ClusterConfigUtil;
import com.ternnetwork.clustersyn.util.FileAlterationUtil;
import com.ternnetwork.clustersyn.util.FtpServerUtil;

public class ClusterSynStarter {

	
	private static final Logger log = Logger.getLogger(ClusterSynStarter.class);
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		File directory = new File("");// 参数为空
        String projectRoot = directory.getCanonicalPath().replaceAll("\\\\","/").replaceAll("/bin", "");
		PropertyConfigurator.configure(projectRoot+"/conf/log4j.properties");
		Cluster cluster=ClusterConfigUtil.getCluster();
		List<ServerNode> serverNodeList=cluster.getServerNodeList();
		String  hostAddress=getHostAddress();
		log.info("host Address:"+hostAddress);
		for(ServerNode serverNode:serverNodeList){
			if(serverNode.getIp().equals(hostAddress)){//只启动当前的服务器节点
			   List<BaseUser> ftpUserList=new ArrayList<BaseUser>();
			   List<AppInstance> appInstanceList=serverNode.getAppInstanceList();
			    for(AppInstance appInstance:appInstanceList){
				    
				   if("local".equals(appInstance.getStorageType())){
					      BaseUser ftpUser = new BaseUser();
						  ftpUser.setName(appInstance.getFtpUserName());
						  ftpUser.setPassword(appInstance.getFtpPassword());
						  ftpUser.setHomeDirectory(appInstance.getFtpHomeDirectory());
						  ftpUserList.add(ftpUser);
						  
						  if(appInstance.getBroadcast()==true){
						    	List<String> synDirList=appInstance.getSynDirList();
							    for(String synDir:synDirList){
							    	String path=appInstance.getFtpHomeDirectory()+synDir;
							    	FileAlterationUtil.createFileAlterationInstance(path, 5000L);
							    }
						  }
				   }
				 
				    
				
			    }
			   FtpServerUtil.createServer(ftpUserList, serverNode.getFtpPort());
			}
		}
		
		

	}


	public static String getHostAddress(){
		
		InetAddress addr;
		try {
			addr = InetAddress.getLocalHost();
			return addr.getHostAddress();//获得本机IP
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	

}
